package com.location.footprint.fragment;

import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.Dialog;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.allen.library.SuperTextView;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.Circle;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.location.footprint.R;
import com.location.footprint.adapter.MapBottomAdapter;
import com.location.footprint.bean.MapBottomBean;
import com.location.footprint.bean.MapMarkerBean;
import com.location.footprint.overlay.MarkerOverlay;
import com.location.footprint.utils.LogUtil;
import com.location.footprint.utils.Utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class MapFragment extends BaseFragment implements AMap.OnMapLoadedListener, AMap.OnCameraChangeListener, AMapLocationListener, LocationSource {
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.linerLayout)
    LinearLayout linerLayout;
    @BindView(R.id.bottomText)
    SuperTextView bottomText;
    @BindView(R.id.mapview)
    MapView mapView;
    @BindView(R.id.img_update)
    ImageView imgUpdate;
    public static final int STROKE_COLOR = Color.parseColor("#A64D73B3");// 定位范围线条颜色
    public static final int FILL_COLOR = Color.parseColor("#0D4D73B3");// 定位范围的填充颜色
    private String mTitle;
    private AMap mMap;
    private AMapLocationClient mLocationClient;
    private AMapLocationClientOption mLocationOption;
    private boolean mFirstFix = true;
    private Circle mCircle;
    private MarkerOverlay markerOverlay;
    private BottomSheetBehavior<LinearLayout> bottomSheetBehavior;
    private AlertDialog.Builder builder;
    private ObjectAnimator rotate;

    public static MapFragment getInstance(String title) {
        MapFragment sf = new MapFragment();
        sf.mTitle = title;
        return sf;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_map;
    }

    @Override
    protected void initView() {
        LogUtil.e(mTitle);
        if (mMap == null) {
            mMap = mapView.getMap();
            setUpMap();
            mMap.setOnMapLoadedListener(this); //地图加载完成监听
            mMap.setOnCameraChangeListener(this);
        }
        initSheetBottom();


    }

    private void initSheetBottom() {
        List<MapBottomBean> mList = new ArrayList<>();
        MapBottomBean bottomBean = new MapBottomBean("文字", R.mipmap.ic_panel_common_text);
        MapBottomBean bottomBean1 = new MapBottomBean("图片", R.mipmap.ic_panel_common_img);
        MapBottomBean bottomBean2 = new MapBottomBean("音频", R.mipmap.ic_panel_common_audio);
        MapBottomBean bottomBean3 = new MapBottomBean("视频", R.mipmap.ic_panel_common_video);
        MapBottomBean bottomBean4 = new MapBottomBean("踩一踩", R.mipmap.ic_panel_common_footprint);
        MapBottomBean bottomBean5 = new MapBottomBean("到此一游", R.mipmap.ic_panel_common_visitit);
        mList.add(bottomBean);
        mList.add(bottomBean1);
        mList.add(bottomBean2);
        mList.add(bottomBean3);
        mList.add(bottomBean4);
        mList.add(bottomBean5);
        MapBottomAdapter mAdapter = new MapBottomAdapter();
        mAdapter.setNewData(mList);
        recyclerview.setLayoutManager(new GridLayoutManager(getContext(), 4, GridLayoutManager.VERTICAL, false));
        recyclerview.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                switch (position) {
                    case 0:
                        showTextImg();
                        break;
                    case 1:
                        showTextImg();
                        break;
                    case 5:
                        showVisiting();
                        break;
                    default:

                        break;

                }
            }
        });
        bottomSheetBehavior = BottomSheetBehavior.from(linerLayout);
        bottomSheetBehavior.setState(BottomSheetBehavior.STATE_DRAGGING);
        bottomSheetBehavior.setPeekHeight(Utils.dip2px(getContext(), 45));
        bottomText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
            }
        });
        imgUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mFirstFix = true;
                mMap.clear();
                if (null != mLocationClient) {
                    LogUtil.e("开始定位刷新数据");
                    startRotate();
                    mLocationClient.startLocation();
                }

            }
        });
        bottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View view, int i) {
                switch (i) {
                    case BottomSheetBehavior.STATE_EXPANDED: //展开
                        imgUpdate.setVisibility(View.GONE);
                        break;
                    case BottomSheetBehavior.STATE_COLLAPSED: //折叠
                        imgUpdate.setVisibility(View.VISIBLE);
                        break;
                    case BottomSheetBehavior.STATE_DRAGGING: //托起
                        imgUpdate.setVisibility(View.GONE);
                        break;
                    case BottomSheetBehavior.STATE_SETTLING: //下滑

                        break;

                }
            }

            @Override
            public void onSlide(@NonNull View view, float v) {
                //这里是拖拽中的回调，slideOffset为0-1 完全收起为0 完全展开为1
            }
        });
    }


    /**
     * 设置一些amap的属性
     */
    private void setUpMap() {
        startRotate();
        mMap.setLocationSource(this);// 设置定位监听
        mMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        mMap.getUiSettings().setZoomControlsEnabled(false);
        mMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        // 设置定位的类型为定位模式 ，可以由定位、跟随或地图根据面向方向旋转几种
//        mMap.setMyLocationType(MyLocationStyle.LOCATION_TYPE_MAP_ROTATE_NO_CENTER);
    }

    /**
     * 定位成功后回调函数
     */
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        stopRotate();
        if (aMapLocation == null || aMapLocation.getErrorCode() != AMapLocation.LOCATION_SUCCESS) {
            Toast.makeText(getContext(), aMapLocation.getErrorInfo() + "  " + aMapLocation.getErrorCode(), Toast.LENGTH_LONG).show();
            return;
        }
        LogUtil.e("刷新数据成功");
        LatLng curLatLng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
        if (mFirstFix) {
            mFirstFix = false;
            addCircle(curLatLng, aMapLocation.getAccuracy());//添加定位精度圆
            markerOverlay = new MarkerOverlay(mMap, curLatLng, getContext());//添加定位图标
//            mSensorHelper.setCurrentMarker(markerOverlay.getCenterMarker());//定位图标旋转
//            mSensorHelper.setCurrentMarker(markerOverlay.getDirectionMarker());//定位图标旋转
            List<MapMarkerBean> list = randomGenerateLatLngs(curLatLng);
            markerOverlay.initPointList(list);
//            markerOverlay.zoomToSpanWithCenter();
            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(curLatLng, 16));
            mLocationClient.stopLocation();
        }

    }

    private void addCircle(LatLng latlng, double radius) {
        CircleOptions options = new CircleOptions();
        options.strokeWidth(1f);
        options.fillColor(FILL_COLOR);
        options.strokeColor(STROKE_COLOR);
        options.center(latlng);
        options.radius(500);
        mCircle = mMap.addCircle(options);
    }

    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        if (mLocationClient == null) {
            mLocationClient = new AMapLocationClient(getContext().getApplicationContext());
            mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mLocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mLocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mLocationClient.startLocation();
        }
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();

        mapView.onPause();
        deactivate();
        mFirstFix = false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (markerOverlay != null) {
            markerOverlay.removeFromMap();
        }
        markerOverlay = null;
        if (mapView != null) {
            mapView.onDestroy();
        }
        if (null != mLocationClient) {
            mLocationClient.onDestroy();
        }
        mLocationClient=null;
    }

    private void showVisiting() {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_visiting, null);
        ImageView img_cancle = view.findViewById(R.id.img_cancle);
        builder = new AlertDialog.Builder(getContext()).setView(view);
        Dialog dialog = builder.create();
        dialog.show();
        img_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    private void showTextImg() {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.dialog_text_img, null);
        ImageView img_cancle = view.findViewById(R.id.img_cancle);
        builder = new AlertDialog.Builder(getContext()).setView(view);
        Dialog dialog = builder.create();
        dialog.show();
        img_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    private void startRotate() {
        if (rotate == null) {
            rotate = ObjectAnimator.ofFloat(imgUpdate, "rotation", 0f, 359f);
            rotate.setInterpolator(new AccelerateDecelerateInterpolator());
            rotate.setDuration(1000);
            rotate.setRepeatCount(ValueAnimator.INFINITE);
            rotate.start();
        } else {
            rotate.start();
        }


    }

    private void stopRotate() {
        if (rotate != null && rotate.isRunning()) {
            rotate.pause();
            rotate = null;
        }

    }

    @Override
    protected void initData() {

    }

    /**
     * 生成以中心点附近指定radius内的坐标数组
     *
     * @return
     */
    private ArrayList<MapMarkerBean> randomGenerateLatLngs(LatLng curLatLng) {
        ArrayList<MapMarkerBean> latLngs = new ArrayList<>();
        double lat = curLatLng.latitude;
        double lng = curLatLng.longitude;
        for (int i = 0; i < 100; i++) {
            double newLat = lat + (10 - (Math.random() * 20)) / Math.pow(10, new Random().nextInt(3) + 1);
            double newLng = lng + (10 - (Math.random() * 20)) / Math.pow(10, new Random().nextInt(3) + 1);
            LatLng newLatLng = new LatLng(newLat, newLng);
            MapMarkerBean bean = new MapMarkerBean();
            int num = (int) (Math.random() * 10 + 1);
            String path = "http://q1.qlogo.cn/g?b=qq&s=640&nk=98648379" + num;
            bean.setLatLng(newLatLng);
            bean.setImgPath(path);

            if (mCircle.contains(newLatLng)) {
                latLngs.add(bean);
            }
        }
        // 如果随机生成的数组个数为0，则再随机添加一个距离中心点更近的坐标
        if (latLngs.size() == 0) {
            MapMarkerBean bean = new MapMarkerBean();
            bean.setLatLng(new LatLng(lat + (Math.random() > 0.5 ? 1 : -1) / Math.pow(10, 3), lng + (Math.random() > 0.5 ? 1 : -1) / Math.pow(10, 3)));
            latLngs.add(bean);
        }
        return latLngs;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        mapView.onCreate(savedInstanceState);// 此方法必须重写.
        return rootView;
    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {

    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {

    }

    @Override
    public void onMapLoaded() {

    }
}